package com.ruiysoft.service.order.facade;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruiysoft.entity.common.UserInfo;
import com.ruiysoft.entity.order.OrderMain;
import com.ruiysoft.entity.order.OrderPay;
import com.ruiysoft.entity.order.OrderReceiverInfo;
import com.ruiysoft.pub.core.Result;
import com.ruiysoft.pub.core.ResultCode;
import com.ruiysoft.pub.core.ResultGenerator;
import com.ruiysoft.pub.entity.PageInfo;
import com.ruiysoft.service.order.IOrderMainService;
import com.ruiysoft.service.order.IOrderPayService;
import com.ruiysoft.service.order.IOrderReceiverInfoService;
import com.ruiysoft.service.order.consts.OrderDBStatusEnum;
import com.ruiysoft.service.order.consts.OrderPayStatusEnum;
import com.ruiysoft.util.CollectionUtil;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Date : 2018/11/10
 *
 * @author WenJialu
 */
@Component
public class OrderWechatFacade {

    @Resource
    private IOrderMainService orderMainService;
    @Resource
    private IOrderPayService orderPayService;
    @Resource
    private IOrderReceiverInfoService orderReceiverInfoService;
    @Resource
    private OrderPubFacade oPubFacade;


    public OrderMain getOrderMain(String orderNo) {
        OrderMain orderMain = oPubFacade.getOrderMain(orderNo);
        return null == orderMain || orderMain.getDelFlag() ? null : orderMain;
    }

    /**
     * 获取所有订单主表列表
     *
     * @param userId
     * @return
     */
    public List<OrderMain> getOrders(Long userId, Long shopId) {
        if (null == userId || null == shopId) {
            return Collections.emptyList();
        }
        return orderMainService.list(new QueryWrapper<OrderMain>()
                .eq("user_id", userId)
                .eq("shop_id", shopId)
                .eq("del_flag", false)
                .orderBy(false, false, "create_time"));
    }

    /**
     * 获取符合用户查询状态的订单
     *
     * @param userId
     * @param statusSet
     * @return
     */
    public List<OrderMain> getOrdersByStatus(Long userId, Long shopId, Set<Integer> statusSet) {
        if (null != statusSet && !statusSet.isEmpty() && !OrderDBStatusEnum.existsStatus(statusSet)) {
            return Collections.emptyList();
        }
        //TODO 数据量还不大，暂时这么写吧，待优化
        //获取该用户所有订单
        List<OrderMain> allOrders = getOrders(userId, shopId);
        if (allOrders.isEmpty()) {
            return Collections.emptyList();
        } else {
            //筛选符合用户查询状态的订单
            if (null == statusSet || statusSet.isEmpty()) {
                return allOrders;
            } else {
                return allOrders.stream().filter(orderMain -> statusSet.contains(orderMain.getStatus())).collect(Collectors.toList());
            }
        }
    }

    /**
     * 获取分页订单主表列表
     *
     * @param userInfo
     * @param customerStatus
     * @param pageStart
     * @param pageSize
     * @return
     */
    public PageInfo<OrderMain> getOrdersByCustomerStatusPage(UserInfo userInfo, @Valid Set<Integer> customerStatus, @NotNull @Valid Integer pageStart, @NotNull @Valid Integer pageSize) {
        if (null == pageStart
                || null == pageSize
                || 0 >= pageSize) {
            return new PageInfo<>();
        }
        //TODO 数据量还不大，暂时这么写吧，待优化
        //筛选符合用户查询状态的订单
        List<OrderMain> orders = getOrdersByStatus(userInfo.getPersonnelId(), userInfo.getShopId(), customerStatus);
        if (orders.isEmpty()) {
            return new PageInfo<>();
        }
        long totalCount = orders.size();
        //计算角标
        int pageStartF = 0 >= pageStart ? 1 : pageStart;
        int fromIndex = (pageStartF - 1) * pageSize;
        int toIndex = fromIndex + pageSize;
        toIndex = toIndex > (int) totalCount ? (int) totalCount : toIndex;
        //切割订单列表(分页)
        List<OrderMain> subList = CollectionUtil.INSTANCE.subList(orders, fromIndex, toIndex);
        return new PageInfo<>(subList, pageStart, pageSize, totalCount);
    }

    public OrderReceiverInfo getLastestReceiverInfo(Long userId) {
        return Optional.ofNullable(userId)
                .map(id -> orderReceiverInfoService.getOne(
                        new QueryWrapper<OrderReceiverInfo>()
                                .eq("user_id", id)
                                .orderBy(false, false, "create_time")
                                .last(" LIMIT 1")))
                .orElse(null);
    }

    public Result orderMainCancel(String orderNo, Long userId, String remark) {
        boolean update = orderMainService.update(
                new OrderMain()
                        .setStatus(OrderDBStatusEnum.ORDER_CANCELLED.getCode())
                        .setCancelTime(new Date())
                        .setRemark(remark),
                new QueryWrapper<OrderMain>()
                        .eq("order_no", orderNo)
                        .eq("user_id", userId)
                        .in("status", OrderDBStatusEnum.getDBStatusCancelable())
                        .eq("del_flag", false));
        return update ? ResultGenerator.genSuccessResult() : ResultGenerator.genFailResult("该订单不可取消");
    }

    public void orderPayCancel(String orderNo) {
        OrderPay opRecord = new OrderPay()
                .setStatus(OrderPayStatusEnum.PAY_CANCEL.getCode())
                .setUpdateTime(new Date())
                .setMessage("支付超时自动取消");
        orderPayService.update(opRecord
                , new QueryWrapper<OrderPay>()
                        .eq("order_no", orderNo)
                        .eq("status", OrderPayStatusEnum.WAITING_FOR_PAY.getCode()));

    }


    //@SuppressWarnings("Duplicates")
    public Result orderVirtualCoinPaid(OrderMain lastOrderMain, Long userId) {
        boolean update = orderMainService.update(
                lastOrderMain,
                new QueryWrapper<OrderMain>()
                        .eq("id", lastOrderMain.getId())
                        .eq("order_no", lastOrderMain.getOrderNo())
                        .eq("user_id", userId)
                        .eq("del_flag", false));
        return update ? ResultGenerator.genSuccessResult() : ResultGenerator.genFailResult("该订单不可取消");
    }


    public Result<OrderMain> orderConfirmReceipt(String orderNo, Long userId) {

        Result<OrderMain> result = new Result<OrderMain>();
        QueryWrapper<OrderMain> entityWrapper = new QueryWrapper<OrderMain>();
        entityWrapper.eq("order_no", orderNo)
                .eq("user_id", userId)
                //状态属于已经发货或系统自动签收
                .in("status", Arrays.asList(OrderDBStatusEnum.DELIVERED.getCode(), OrderDBStatusEnum.SYSTEM_SIGNED.getCode()))
                .eq("del_flag", false);

        OrderMain orderMain = orderMainService.getOne(entityWrapper);
        if (orderMain == null) {
            result.setBizCode(ResultCode.CODE_COMMON_ERROR);
            result.setBizMessage("无此订单或当前不可\"确认收货\".");
            return result;
        }
        orderMain.setStatus(OrderDBStatusEnum.RECEIVED.getCode());
        if (orderMain.getFinalSignTime() == null) {
            orderMain.setFinalSignTime(new Date());
        }
        result.setData(orderMain);
        boolean update = orderMainService.update(orderMain, entityWrapper);
        if (update) {
            result.setBizCode(ResultCode.CODE_SUCCESS);
        } else {
            result.setBizCode(ResultCode.CODE_COMMON_ERROR);
            result.setBizMessage("未能更新订单状态，请稍后再试.");
        }
        return result;
    }
}
